<template>
  <basic-container>
    <!--需求沟通模块-->
    <!-- 搜索框功能代码段 -->
    <beetles-search :size="'mini'" @search-form="searchForm" @empty-form="emptyForm" :expend="false">
      <div class="beetles-search-from" :style="{height:searchConceal? 'auto' :'40px'}" style="overflow:hidden" slot-scope="{searchConceal}"
           slot="searchForm">
        <el-form ref="form" :model="form" :inline="true" label-width="100px"
                 @submit.native.prevent>
          <el-form-item label="需求ID:">
            <el-input
              placeholder="请输入内容"
              v-model="form.strShortId"
              size="mini"
              clearable
              @clear="searchForm">
            </el-input>
          </el-form-item>
          <el-form-item label="媒体:">
            <el-select id="id-offer-creativerequest-isShowSelectOptions-submitForm"
                       v-model="form.platform" clearable size="mini" placeholder="请选择媒体"
                       ref="requestPlatform" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in platformList"
                :key="item.value"
                :label="item.dictValue"
                :value="item.dictKey">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="制作状态:">
            <el-select id="id-offer-creativerequest-isShowSelectOptions-submitForm-one"
                       v-model="form.status" clearable size="mini" placeholder="请选择制作状态"
                       ref="requestStatus" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in productionStatus"
                v-if="userInfo.detail.tenantVariables['ENABLE_REQUEST_DETAIL_AUDIT'] == 'true' || (item.value != 4 && item.value != 5)"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设计师:">
            <el-select id="id-offer-creativerequest-isShowSelectOptions-submitForm-tow"
                       v-model="form.designers" clearable filterable size="mini" placeholder="请选择设计师"
                       ref="requestDesigners" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in designerList"
                :key="item.id"
                :label="item.realName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="需求方:">
            <el-select id="id-offer-creativerequest-isShowSelectOptions-submitForm-3"
                       v-model="form.requester" clearable filterable size="mini"
                       placeholder="请选择需求方" @change="searchForm">
              <el-option
                v-for="item in requesterList"
                :key="item.id"
                :label="item.realName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="紧急程度:">
            <el-select id="id-offer-creativerequest-unfoldIcon-searchForm-4"
                       v-model="form.urgency" clearable size="mini" placeholder="请选择紧急程度"
                       ref="requestUrgency" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in urgencyList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态:">
            <el-select id="id-offer-creativerequest-unfoldIcon-searchForm-5"
                       v-model="form.autoAuditStatus" clearable size="mini" placeholder="请选择审核状态"
                       ref="requestAutoAuditStatus" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in auditStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="素材类型:">
            <el-select id="id-offer-creativerequest-unfoldIcon-searchForm-6"
                       v-model="form.creativeType" clearable size="mini" placeholder="请选择素材类型"
                       ref="requestCreativeType" @visible-change="isShowSelectOptions" @change="searchForm">
              <el-option
                v-for="item in createType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间:">
            <el-date-picker
              id="id-offer-creativerequest-submissionTime-pickerOptions"
              v-model="submissionTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              unlink-panels
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              style="width: 70%">
            </el-date-picker>
          </el-form-item>
        </el-form>
      </div>
    </beetles-search>
    <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   :view-name="'creativerequest'"
                   :page.sync="page"
                   :permission="permissionList"
                   :before-open="beforeOpen"
                   :row-class-name-rollback="getRowClassName"
                   v-model="form"
                   ref="crud"
                   @row-del="rowDel"
                   @search-change="searchChange"
                   @search-reset="searchReset"
                   @selection-change="selectionChange"
                   @current-change="currentChange"
                   @size-change="sizeChange"
                   @refresh-change="refreshChange"
                   @on-load="onLoad">
      <template slot-scope="{row}" slot="shortId">
        <el-link underline @click="handleCheck(row)">{{ row.shortId }}</el-link>
      </template>
      <template slot-scope="{row}" slot="requesterName">
        <div>
          <el-tag type="mini">{{ row.requesterName }}</el-tag>
        </div>
      </template>
      <template slot-scope="{row}" slot="designerName">
        <div style="display:flex;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
          <div style="margin-left: 5px" v-for="(tag,index) in designersTagList(row.designerName)" :key="index">{{
              tag
            }}
          </div>
        </div>
      </template>
      <template slot-scope="{row}" slot="platform">
        <div style="display: flex;flex-wrap: wrap;">
          <div style="width: 20px;margin-right: 4px"
               v-for="(item,index) in platformLogo(row.platform)"
               :key="index">
            <img style="width: 100%" :src="item.url" :title="item.name">
          </div>
        </div>
      </template>
      <template slot-scope="{row}" slot="content">
          <div>
            {{filterText(row.content)}}
          </div>
      </template>

      <template slot-scope="{row}" slot="creativeType">
        <div>
          <el-tag type="mini" v-if="row.creativeType.indexOf('0') > -1">图片</el-tag>
          <el-tag type="mini" v-if="row.creativeType.indexOf('1') > -1">视频</el-tag>
        </div>
      </template>
      <template slot="menuLeft">
        <el-button id="id-offer-creativerequest-handleAdd"
                   type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   v-if="userRole.optimize"
                   @click="handleAdd">新 增
        </el-button>
        <el-button id="id-offer-creativerequest-handleDelete"
                   type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="userRole.admin || userRole.optimize"
                   @click="handleDelete">删 除
        </el-button>
        <!--        <el-button type="warning"-->
        <!--                   size="small"-->
        <!--                   icon="el-icon-download"-->
        <!--                   plain-->
        <!--                   v-if="userRole.optimize || userRole.designer"-->
        <!--                   @click="handleExport">导 出-->
        <!--        </el-button>-->
      </template>
      <template slot-scope="{type,size,row}" slot="menu">
        <el-tooltip content="查看" placement="top">
          <el-button size="small" icon="el-icon-view" type="text" @click="handleCheck(row)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="编辑" placement="top">
          <el-button icon="el-icon-edit" type="text" @click="handleEdit(row)"
                     :disabled="!(row.status !== 9  && showEdit(row)) || row.demandStatus===1"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="上传" placement="top">
          <el-button icon="el-icon-upload2" type="text" @click="handleUpload(row)"
                     :disabled="!(userRole.designer && [1,2,3].includes(row.status)) || row.demandStatus===1"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="复制" placement="top">
          <el-button icon="el-icon-document-copy" type="text" @click="handleCopy(row)"
                     :disabled="!(userRole.optimize)"></el-button>
        </el-tooltip>
        <span style="padding-left: 10px;"></span>
        <el-tooltip content="删除" placement="top">
          <el-button icon="el-icon-delete" type="text" @click="rowDel(row)"
                     :disabled="!(row.status !== 9  && (userRole.admin || userRole.optimize))"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>

    <div v-if="uploaddialogVisible">
      <el-dialog :visible.sync="uploaddialogVisible"
                 :modal-append-to-body="false"
                 :close-on-click-modal="false" :before-close="handleUploadClose" :append-to-body="true" width="80%">
        <div slot="title" style="font-weight: 600;font-size: 15px">
          上传素材 <span style="font-size: 14px;color: #666666">(需求ID: {{detailInfo.shortId}} 需求名称: {{ uploadTitle }})</span>
        </div>
        <product-creative :request-detail-info="detailInfo" :offerInfo="offerInfo"
                          :close="handleUploadClose" :is-creative-still-request="1"></product-creative>
      </el-dialog>
    </div>
    <div v-if="dialogOpen">
      <request-dialog :requestid="creativerequestid" :title="dialogType" :dialogVisible="dialogOpen"
                      :detail-info="detailInfo"
                      :offerId="dialogOfferId" :dataList="dataList" :userRole="userRole" :offerInfo="offerInfo"
                      @close-dialog="closeDialog"></request-dialog>
    </div>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  remove,
  getUserRole,
  getOfferDesigner,
  getRequestUserList,
  getOfferOptimizer
} from "@/api/offer/creativerequest";
import {getDetail as getOfferDetail} from "@/api/business/offer";
import {mapGetters} from "vuex";
import {createEventHandler} from "@/util/events";
import {createWebSocket} from "@/util/ws";
import requestDialog from "./components/request-dialog"
import productCreative from "./components/creativeRequest-components/productCreative"
import beetlesTable from "@/components/basic-components/beetles-table"
import {findObject} from "@/util/util";
import {getSysDictList} from "@/api/system/dict";
import {platformLogo} from "@/util/beetles";
import beetlesSearch from "@/components/basic-components/beetles-search"
import func from "@/util/func";


export default {
  components: {requestDialog, productCreative, beetlesTable, beetlesSearch},

  data() {

    return {
      loadInitParams: false,
      detailInfo: {},
      uploaddialogVisible: false,
      uploadTitle: '',
      creativerequestid: null,
      upIcon: 'el-icon-arrow-down',
      searchIcon: 'el-icon-search',
      emptyIcon: 'el-icon-delete',
      searchConceal: false,
      demand: [],
      requesterList: [],
      userRole: {
        designer: true,
        designerManager: true,
        optimize: true,
        admin: true
      },//用户角色
      form: {
        platform: null,
        status: null,
        autoAuditStatus: null,
        creativeType: null,
        urgency: null,
        designers: null,
        beginDate: null,
        endDate: null,
        requester: null,
      },
      submissionTime: null,
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      dataList: {},
      selectionList: [],
      dialogType: '', //弹窗类型
      dialogOpen: false, //弹窗是否打开
      dialogOfferId: null,
      platformList: '',
      productionStatus: [
        {label: '需求待审核', value: 4},
        {label: '需求已拒绝', value: 5},
        {value: 0, label: "待分配"},
        {value: 1, label: "制作中"},
        {value: 2, label: "待确认"},
        {value: 3, label: "已确认"},
      ],
      auditStatusList: [
        {value: 0, label: "待审核"},
        {value: 2, label: "审核完成"},
        {value: 3, label: "全部拒绝"},
        {value: 5, label: "部分通过"},
      ],
      createType: [
        {value: 0, label: "图片"},
        {value: 1, label: "视频"},
      ],
      urgencyList: [
        {label: '一般', value: 0},
        {label: '紧急', value: 1},
      ],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近两周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
            picker.$emit('pick', [start, end]);
          }
        },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '所有',
            onClick(picker) {
              const end = "";
              const start = "";
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      option: {
        emptyText: '数据为空',
        // height:'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        menuWidth: 200,
        searchMenuSpan: 6,
        delBtn: false,
        editBtn: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: "需求ID",
            prop: "shortId",
            overHidden: true,
          },
          {
            label: "名称",
            prop: "name",
            viewDisplay: false,
            overHidden: true,
          },
          {
            label: "媒体",
            prop: "platform",
            // multiple: true,
            // type: 'select',
            // dataType: 'string',
            // dicData: [
            //   {'dictKey': 'facebook', 'dictValue': 'Facebook'},
            //   {'dictKey': 'google', 'dictValue': 'Google'},
            //   {'dictKey': 'bigo', 'dictValue': 'Bigo'},
            //   {'dictKey': 'tiktok', 'dictValue': 'TikTok'}
            // ],
            // props: {
            //   label: "dictValue",
            //   value: "dictKey"
            // },
            // searchMultiple: true,
            // rules: [{
            //   required: true,
            //   message: "请输入媒体",
            //   trigger: "blur"
            // }],
          },
          {
            label: "需求内容",
            prop: "content",
            overHidden: true,
          },
          {
            label: "制作状态",
            prop: "status",
            dicData: [
              {label: '需求待审核', value: 4},
              {label: '需求已拒绝', value: 5},
              {label: '待分配', value: 0},
              {label: '制作中', value: 1},
              {label: '待确认', value: 2},
              {label: '已确认', value: 3},
              {label: '已删除', value: 9},
            ],
            type: 'select'
          },
          {
            label: "审核状态",
            prop: "autoAuditStatus",
            dicData: [
              {label: '待审核', value: 0},
              {label: '审核完成', value: 2},
              {label: '全部拒绝', value: 3},
              {label: '部分通过', value: 5},
            ],
            type: 'select'
          },
          {
            label: "素材类型",
            prop: "creativeType",
            dicData: [
              {label: '图片', value: '0'},
              {label: '视频', value: '1'},
            ],
            type: 'select'
          },
          {
            label: "紧急程度",
            prop: "urgency",
            dicData: [
              {label: '一般', value: 0},
              {label: '紧急', value: 1},
            ],
            type: 'select'
          },
          {
            label: "需求方",
            prop: "requesterName",
            slot: true,
            rules: [{
              required: true,
              message: "请输入需求方",
              trigger: "blur"
            }]
          },
          {
            label: "设计师",
            prop: "designerName",
            overHidden: true,
            width: 120,
            rules: [{
              required: false,
              message: "请输入设计师",
              trigger: "blur"
            }],
            dicUrl: '/api/beetles-business/offer/get-designer-select',
            props: {
              label: "realName",
              value: "id"
            }
          },
          {
            label: "创建时间",
            prop: "createTime",
            width: 120
          },
          {
            label: "最新上传时间",
            prop: "uploadTime",
            width: 120
          },
          {
            label: "优化师验收时间",
            prop: "auditTime",
            width: 120
          },
        ]
      },
      data: [],
      currOpRowId: '',
      designerList: [],
      offerInfo: null,
    };
  },
  beforeRouteLeave(to, form, next) {
    let self = this;
    if (self.socket) {
      self.socket.close();
      self.socket = null;
    }
    if (self.eventHandler) {
      self.eventHandler.clear();
    }
    next();
  },
  created() {

    getSysDictList('platforms').then(map => {
      this.platformList = map['platforms'];
      let column = findObject(this.option.column, 'platform', 'prop')
      if (column != null) {
        column.dicData = map['platforms'];
      }
    });
    //window.addEventListener('keyup', this.searchForm) //监听键盘事件
    let self = this;
    this.eventHandler = createEventHandler("offerCenter")
      .addListener((event) => {
        if (event.message == 'offerChanged' && event.offerId && event.offerId !== "") {
          self.offer = event.offerId;
          this.loadInitParams = false;
          self.loadOfferDetail();
          self.onLoad(self.page);
        }
        if (event.message == 'initPage' && event.offerId && event.offerId !== "") {
          setTimeout(() => {
            self.initPage();
          }, 500);
        }
      });
    getOfferOptimizer(this.offer).then(res => {
      this.demand = res.data.data
    })
  },
  mounted() {
    this.loadOfferDetail();
    getUserRole().then(res => {
      let roleList = res.data.data.split(',');
      this.userRole.designerManager = roleList.includes('designer_manager') || roleList.includes('admin');
      this.userRole.designer = roleList.includes('designer') || roleList.includes('admin') || roleList.includes('designer_manager');
      this.userRole.optimize = roleList.includes('optimizer') || roleList.includes('admin');
      this.userRole.admin = roleList.includes('admin');
    })

    let self = this;
    self.isRefreshing = false;
    if (!self.socket) {
      self.socket = createWebSocket('/api/blade-system/wss', 'json');
      if (self.socket) self.socket.ontextmessage = (msg) => {
        let msgObj = JSON.parse(msg);
        //console.log("socket receive:" + msg)
        if (msgObj) {
          if (!self.isRefreshing && msgObj.messageName === 'tenantMessage' && msgObj.data.messageName === 'creativeRequestChanged') {
            if (msgObj.data.creativeRequestIds != null) {
              let creativeRequestIdList = msgObj.data.creativeRequestIds.split(",");
              if (self.data.find((v) => {
                return creativeRequestIdList.includes(v.id);
              }) == null) {
                return;
              }
            }
            self.isRefreshing = true;
            //不可以频繁刷新，如果有刷新需求，延迟5秒刷新，在延迟期间，有新的刷新需求均不会多次触发onLoad
            setTimeout(() => {
              self.onLoad(self.page);
              self.isRefreshing = false;
            }, 5000);
          }
        }
      };
      if (self.socket) self.socket.onerror = () => {
        this.$message({
          type: 'warning',
          message: '您的网络目前不稳定，数据可能不能自动刷新！'
        });
      };
    }
    setTimeout(() => {
      self.initPage();
    }, 500);
  },
  computed: {
    ...mapGetters(["permission", "offer", "userInfo"]),
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    async loadDesignerList() {
      this.form.designers = ''
      await getRequestUserList(this.offer, '', 'designer').then(res => {
        this.designerList = res.data.data;
        this.designerList.forEach(user => {
          if (user.id == this.userInfo.user_id) {
            this.form.designers = user.id;
          }
        });
      });
    },
    async loadRequesterList() {
      this.form.requester = ''
      await getRequestUserList(this.offer, '', 'requester').then(res => {
        this.requesterList = res.data.data;
        this.requesterList.forEach(user => {
          if (user.id == this.userInfo.user_id) {
            this.form.requester = user.id;
          }
        });
      });
    },
    loadOfferDetail() {
      getOfferDetail(this.offer).then(res => {
        this.offerInfo = res.data.data;
      });
    },
    unfoldIcon() {
      if (this.upIcon === 'el-icon-arrow-down') {
        this.upIcon = 'el-icon-arrow-up'
        this.searchConceal = true
      } else {
        this.upIcon = 'el-icon-arrow-down'
        this.searchConceal = false
      }
    },
    isShowSelectOptions(isShowSelectOptions) {
      if (!isShowSelectOptions) this.$refs.requestPlatform.blur();
      if (!isShowSelectOptions) this.$refs.requestStatus.blur();
      if (!isShowSelectOptions) this.$refs.requestAutoAuditStatus.blur();
      if (!isShowSelectOptions) this.$refs.requestCreativeType.blur();
      if (!isShowSelectOptions) this.$refs.requestUrgency.blur();
      if (!isShowSelectOptions) this.$refs.requestDesigners.blur();
    },
    //搜索按钮函数
    searchForm() {
      if (this.submissionTime != null) {
        this.form.beginDate = this.submissionTime[0];
        this.form.endDate = this.submissionTime[1];
      } else {
        this.form.beginDate = "";
        this.form.endDate = "";
      }
      this.query = this.form
      this.page.currentPage = 1
      this.onLoad(this.page, this.form)
    },
    //清空按钮函数
    emptyForm() {
      this.form = {
        strShortId: '',
        platform: null,
        status: null,
        autoAuditStatus: null,
        creativeType: null,
        urgency: null,
        designers: null,
        beginDate: null,
        endDate: null,
      }
      this.submissionTime = null
      this.query = this.form
      this.onLoad(this.page, this.form)
    },
    filterText(content){
      // content.innerHTML.replace(/<.*?>/g,"")
      var re1 = new RegExp("<.+?>","g");//匹配html标签的正则表达式，"g"是搜索匹配多个符合的内容
      var msg = content.replace(re1,'');//执行替换成空字符
      return msg;
    },
    initPage() {
      let self = this;
      let initPageInfo = window.sessionStorage.getItem("initPageInfo");
      if (initPageInfo == null || initPageInfo == '') {
        return;
      }
      let param = JSON.parse(initPageInfo);
      let offerId = param.offerId;
      if (self.offer == offerId && param.ropList != null && param.ropList.length > 0) {
        let ropList = [];
        let hasAction = false;
        for (let i = 0; i < param.ropList.length; i++) {
          if (param.ropList[i].rop == 'editCreativeRequest') {
            let rid = param.ropList[i].rid;
            param.ropList[i] = null;
            self.handleEditById(rid);
            hasAction = true;
          } else if (param.ropList[i].rop == 'uploadCreativeRequest') {
            let rid = param.ropList[i].rid;
            param.ropList[i] = null;
            self.handleUploadById(rid);
            hasAction = true;
          } else {
            ropList.push(param.ropList[i]);
          }
        }
        if (hasAction) {
          param.ropList = ropList;
          window.sessionStorage.setItem("initPageInfo", JSON.stringify(param));
        }
      }
    },
    showEdit(row) {
      if (this.userRole.admin || this.userRole.optimize || this.userRole.designerManager || row.designerManager === this.userInfo.user_id) {
        return true
      } else if (this.userRole.designer && row.designers != null) {
        if (row.designers.split(',').includes(this.userInfo.user_id)) {
          return true;
        }
      }
      return false;
    },
    designersTagList(ids) {
      return ids.split(',')
    },
    //查看
    handleCheck(row) {
      console.log(row)
      this.currOpRowId = row.id;
      this.creativerequestid = row.id
      getDetail(row.id).then(res => {
        this.dataList = res.data.data
        this.dialogOfferId = row.offerId;
        this.dialogType = 'check';
        this.openRequestDialog();
      })
      this.detailInfo = row
    },
    openRequestDialog() {
      if (this.offerInfo == null || this.offerInfo.id != this.offer) {
        getOfferDetail(this.offer).then(res => {
          this.offerInfo = res.data.data;
          this.dialogOpen = true;
        });
      } else {
        this.dialogOpen = true;
      }
    },
    //编辑
    handleEditById(id) {
      this.creativerequestid = id
      this.currOpRowId = id;
      getDetail(id).then(res => {
        this.dataList = res.data.data
        this.dialogOfferId = this.offer;
        this.dialogType = 'edit';
        this.openRequestDialog();
      })
    },
    handleEdit(row) {
      this.handleEditById(row.id);
      this.detailInfo = row
    },
    handleUploadById(id) {
      this.creativerequestid = id
      this.currOpRowId = id;
      getDetail(id).then(res => {
        let creativeRequest = res.data.data.creativeRequest;
        console.log('offerInfo')
        console.log(this.offerInfo);
        if (this.offerInfo == null) {
          getOfferDetail(this.offer).then(res => {
            this.offerInfo = res.data.data;
            this.handleUpload(creativeRequest);
          });
        } else {
          this.handleUpload(creativeRequest);
        }
      })
    },
    handleUpload(row) {
      this.uploadTitle = row.name
      this.detailInfo = row
      // console.log('上传detailInfo', this.detailInfo)
      this.uploaddialogVisible = true
    },
    handleUploadClose() {
      this.uploaddialogVisible = false
      this.onLoad(this.page)
    },
    handleCopy(row) {
      let id = row.id;
      this.creativerequestid = id
      this.currOpRowId = id;
      getDetail(id).then(res => {
        this.dataList = res.data.data
        if (this.dataList.creativeRequest.name != null && this.dataList.creativeRequest.name != '') {
          this.dataList.creativeRequest.name = this.dataList.creativeRequest.name + '[复制]';
        }
        this.dialogOfferId = this.offer;
        this.dialogType = 'copy';
        this.openRequestDialog();
      })
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleAdd() {
      this.dataList = null;
      this.dialogOfferId = this.offer;
      this.dialogType = 'add';
      this.openRequestDialog();
    },
    // handleExport() {
    //   this.$message.warning("导出");
    // },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    getRowClassName({row}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    //dialog关闭回调
    closeDialog() {
      this.dialogOpen = false
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      if (this.$refs.crud) {
        this.$refs.crud.toggleSelection();
      }
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    platformLogo(platform) {
      return platformLogo(platform)
    },
    async onLoad(page, params = {}) {
      if (!this.loadInitParams) {
        await this.loadDesignerList();
        await this.loadRequesterList();
        this.query = this.form;
        this.loadInitParams = true;
      }
      this.loading = true
      params.offerId = this.offer
      console.log(this.form);
      console.log(this.query);
      await getList(page.currentPage, page.pageSize, Object.assign(params, this.query), 'createTime').then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        //this.option.column[1].dicData = this.platformList
        this.selectionClear();
      })
    }
  },
  watch: {
    'form.strShortId'() {
      this.$nextTick(() => {
        func.trimPropValue(this.form,'strShortId');
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.hanDer {
  overflow: hidden;
  width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis
}
/deep/ .current-op-row {
  background-color: #f5dab1;
}

.text {
  width: 45px;
  height: 30px;
  float: left;
  font-size: 13px;
  margin-top: 3px;
  color: #72767b
}

.search-circle {
  border-radius: 50%;
  border: 1px solid #dcdfe6;
  width: 30px;
  height: 30px;
  padding: 0;
  margin-right: 0;
}
.beetles-search-from {
  .el-form-item {
    margin-bottom: unset;

    .el-select {
      width: 100%;
    }
  }
}
.el-link {
  font-weight: 400;
}
</style>
